package com.wu.gumomallproduct.product.service.impl;

import com.wu.gumomallproduct.product.service.CategoryBrandRelationService;
import com.wu.common.vo.product.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wu.common.utils.PageUtils;
import com.wu.common.utils.Query;

import com.wu.gumomallproduct.product.dao.CategoryDao;
import com.wu.common.entity.product.CategoryEntity;
import com.wu.gumomallproduct.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Cacheable(value = "category", key = "#root.method.name")
    public List<CategoryEntity> listWithTree() {
//        RReadWriteLock lock = redissonClient.getReadWriteLock("category");
//        lock.readLock().lock();
//        try{
//            System.out.println("获取到读锁");
//            String listWithTree = (String) redisTemplate.opsForValue().get("listWithTree");
//            if (!StringUtils.isEmpty(listWithTree)){
//                return JSON.parseObject(listWithTree, new TypeReference<List<CategoryEntity>>(){});
//            }

            //查出所有分类
            System.out.println("调用了 listWithTree  查询了数据库........【所有分类】");
            List<CategoryEntity> list = this.list();
            List<CategoryEntity> collect = list.stream().filter(category ->
                    category.getParentCid() == 0
            ).map(category -> {
                category.setChildren(getChildrens(category, list));
                return category;
            }).sorted((x,y)->{
                return x.getSort() - y.getSort();
            }).collect(Collectors.toList());
//            redisTemplate.opsForValue().set("listWithTree", JSON.toJSONString(collect));
            return collect;
//        }catch (Exception e){
//
//        }finally {
//            System.out.println("释放读锁");
//            lock.readLock().unlock();
//        }
//        return null;
    }

    @Override
    @Transactional
    @CacheEvict(value = "category", allEntries = true)
    public void updateByCategoryEntity(CategoryEntity category) {
//        RReadWriteLock lock = redissonClient.getReadWriteLock("category");
//        lock.writeLock().lock();
//        try{
//            System.out.println("获取到写锁");
            this.updateById(category);
            if (!StringUtils.isEmpty(category.getName())){
                categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
            }
//            redisTemplate.delete("listWithTree");
//        }catch (Exception e){
//
//        }finally {
//            System.out.println("释放写锁");
//            lock.writeLock().unlock();
//        }

    }

    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> list) {
        List<CategoryEntity> collect = list.stream().filter(category ->
                category.getParentCid() == categoryEntity.getCatId()
        ).map(category -> {
            category.setChildren(getChildrens(category, list));
            return category;
        }).sorted((x,y)->{
            return x.getSort() - y.getSort();
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();

        //递归查询是否还有父节点
        List<Long> parentPath = findParentPath(catelogId, paths);

        //进行一个逆序排列
        Collections.reverse(parentPath);

        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }


    /**
     * 查询一级分类。
     * 父ID是0， 或者  层级是1
     */
    @Override
    @CachePut(value = "category", key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("调用了 getLevel1Categorys  查询了数据库........【一级分类】");
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    @Cacheable(value = "category", key = "#root.method.name")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        // 一次性获取所有 数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        System.out.println("调用了 getCatalogJson  查询了数据库........【三级分类】");
        // 1）、所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2）、封装数据
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), level1 -> {
            // 查到当前1级分类的2级分类
            List<CategoryEntity> category2level = getParent_cid(selectList, level1.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (category2level != null) {
                catalog2Vos = category2level.stream().map(level12 -> {
                    // 查询当前2级分类的3级分类
                    List<CategoryEntity> category3level = getParent_cid(selectList, level12.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (category3level != null) {
                        catalog3Vos = category3level.stream().map(level13 -> {
                            return new Catalog2Vo.Catalog3Vo(level12.getCatId().toString(), level13.getCatId().toString(), level13.getName());
                        }).collect(Collectors.toList());
                    }
                    return new Catalog2Vo(level1.getCatId().toString(), catalog3Vos, level12.getCatId().toString(), level12.getName());
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return collect;
    }

    @Override
    @CacheEvict(value = "category", allEntries = true)
    public void saveCategoryEntity(CategoryEntity category) {
        this.save(category);
    }

    /**
     * 查询出父ID为 parent_cid的List集合
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", level.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {

        //1、收集当前节点id
        paths.add(catelogId);

        //根据当前分类id查询信息
        CategoryEntity byId = this.getById(catelogId);
        //如果当前不是父分类
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }

        return paths;
    }

}